package cn.edkuir.ware.service.impl;

import cn.edkuir.common.utils.R;
import cn.edkuir.ware.feign.MemberFeignService;
import cn.edkuir.ware.vo.FareVo;
import cn.edkuir.ware.vo.MemberAddressVo;
import com.alibaba.fastjson.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.edkuir.common.utils.PageUtils;
import cn.edkuir.common.utils.Query;

import cn.edkuir.ware.dao.WareInfoDao;
import cn.edkuir.ware.entity.WareInfoEntity;
import cn.edkuir.ware.service.WareInfoService;
import org.springframework.util.StringUtils;


@Service("wareInfoService")
public class WareInfoServiceImpl extends ServiceImpl<WareInfoDao, WareInfoEntity> implements WareInfoService {
    @Autowired
    private MemberFeignService memberFeignService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<WareInfoEntity> page = this.page(
                new Query<WareInfoEntity>().getPage(params),
                new QueryWrapper<WareInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<WareInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)) {
            wrapper.eq("id", key)
                    .or().like("name", key)
                    .or().like("address", key)
                    .or().like("areacode", key);
        }

        IPage<WareInfoEntity> page = this.page(
                new Query<WareInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }


    //根据收货地址id计算运费
    @Override
    public FareVo getFareByAddrId(Long addrId) {
        FareVo fareVo = new FareVo();
        fareVo.setFare(new BigDecimal(("0")));
        R r = memberFeignService.info(addrId);
        MemberAddressVo memberAddress = r.getData("memberReceiveAddress", new TypeReference<MemberAddressVo>() {
        });

        fareVo.setAddress(memberAddress);
        if(memberAddress != null) {
            String phone = memberAddress.getPhone();
            phone = phone.substring(phone.length() - 1);
            fareVo.setFare(new BigDecimal(phone));
        }
        return fareVo;
    }

}